package com.auto.survey.activity.config

import android.app.Activity
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.activity.config.entity.PointConfig
import com.google.gson.Gson
import java.util.Collections

class SurveyPointAdapter(activity:Activity) : RecyclerView.Adapter<SurveyPointAdapter.ItemViewHolder>() {
    val mActivity = activity
    var itemTouchHelper: ItemTouchHelper? = null
    private var items: MutableList<PointConfig>?=null
    private var isDeleting = false // 标记是否正在执行删除操作

    fun setItems(data: MutableList<PointConfig>){
        items = data
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_serveypoint_layout, parent, false)
        return ItemViewHolder(view)
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {

        // 检查位置是否有效
        if (position >= items?.size ?: 0) return

        holder.edit_Px.setText("${items?.get(position)?.point_x_data}")
        holder.edit_Py.setText("${items?.get(position)?.point_y_data}")
        holder.edit_Pz.setText("${items?.get(position)?.point_z_data}")
        holder.edit_Ph.setText("${items?.get(position)?.point_mirr_h}")
        holder.edit_Pname.setText(items?.get(position)?.point_name)
        holder.edit_Pnum.setText("${items?.get(position)?.point_mirr_num}")

        holder.edit_Px.addTextChangedListener(EditTextWater(holder.edit_Px, items?.get(position)))
        holder.edit_Py.addTextChangedListener(EditTextWater(holder.edit_Py, items?.get(position)))
        holder.edit_Pz.addTextChangedListener(EditTextWater(holder.edit_Pz, items?.get(position)))
        holder.edit_Ph.addTextChangedListener(EditTextWater(holder.edit_Ph, items?.get(position)))
        holder.edit_Pname.addTextChangedListener(EditTextWater(holder.edit_Pname, items?.get(position)))
        holder.edit_Pnum.addTextChangedListener(EditTextWater(holder.edit_Pnum, items?.get(position)))

        // 删除按钮点击事件
        holder.iv_dele.setOnClickListener {
            if (isDeleting) return@setOnClickListener // 防止重复删除
            val safePosition = holder.adapterPosition
            if (safePosition != RecyclerView.NO_POSITION) {

                AlertDialog.Builder(mActivity)
                    .setTitle("删除提示")
                    .setMessage("确定要删除该测点吗？")
                    .setPositiveButton("确定") { dialog, _ ->
                        deleteItem(safePosition)
                        dialog.dismiss()
                    }
                    .setNegativeButton("取消") { dialog, _ ->
                        dialog.dismiss()
                    }
                    .show()


            }
        }

        // 拖拽句柄
        holder.iv_drag.setOnTouchListener { v, event ->
            if (event.actionMasked == MotionEvent.ACTION_DOWN) {
                itemTouchHelper?.startDrag(holder)
                return@setOnTouchListener true
            }
            return@setOnTouchListener false
        }
    }

    override fun getItemCount(): Int {

        if (items != null && items!!.size > 0) {
            return items!!.size
        }
        return 0
    }


    // 删除项目 - 改进版本
    fun deleteItem(position: Int) {
        if (position < 0 || position >= (items?.size ?: 0)) return

        isDeleting = true
        items?.removeAt(position)
        notifyItemRemoved(position)

        // 如果删除的不是最后一项，需要通知后续项目位置发生了变化
        if (position < itemCount) {
            notifyItemRangeChanged(position, itemCount - position)
        }

        // 添加延迟以确保动画完成
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            isDeleting = false
        }, 300) // 等待300毫秒，根据你的动画时长调整
    }

    // 移动项目（添加缺失的函数）
    fun moveItem(fromPosition: Int, toPosition: Int) {
        // 检查索引是否有效
        val itemList = items ?: return
        if (fromPosition !in itemList.indices || toPosition !in itemList.indices) {
            return
        }

        // 执行移动操作
        Collections.swap(itemList, fromPosition, toPosition)

        // 批量更新 position 属性（更高效）
        itemList.forEachIndexed { index, item ->
            item.position = index
        }


        Log.i("SurveyPointAdapter", "item json = ${Gson().toJson(items)}")
        notifyItemMoved(fromPosition, toPosition)
    }

    inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val edit_Px: EditText = itemView.findViewById(R.id.edit_point_x)
        val edit_Py: EditText = itemView.findViewById(R.id.edit_point_y)
        val edit_Pz: EditText = itemView.findViewById(R.id.edit_point_z)
        val edit_Ph: EditText = itemView.findViewById(R.id.edit_point_h)
        val edit_Pname: EditText = itemView.findViewById(R.id.edit_point_name)
        val edit_Pnum: EditText = itemView.findViewById(R.id.edit_point_num)

        val iv_drag:ImageView = itemView.findViewById(R.id.iv_point_drag)
        val iv_dele:ImageView = itemView.findViewById(R.id.iv_point_delete)
    }

    inner class EditTextWater(val editText: EditText, val point : PointConfig?) : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            when(editText.id){
                R.id.edit_point_x -> point?.point_x_data = s?.toString()?.toDoubleOrNull()?:0.0//测点坐标x
                R.id.edit_point_y-> point?.point_y_data = s?.toString()?.toDoubleOrNull()?:0.0//测点坐标y
                R.id.edit_point_z-> point?.point_z_data = s?.toString()?.toDoubleOrNull()?:0.0//测点坐标z
                R.id.edit_point_h-> point?.point_mirr_h = s?.toString()?.toDoubleOrNull()?:0.0//棱镜高
                R.id.edit_point_name-> point?.point_name = s?.toString().toString()//测点名称
                R.id.edit_point_num-> point?.point_mirr_num = s?.toString()?.toLongOrNull()?:0//测回次数
            }
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

    }
}